{% load static %}
{% extends 'layout.html' %}

{% block title %}商品列表{% endblock %}

{% block extra_head %}
    <!-- Tailwind CSS 和 Font Awesome -->
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
    <style>
        .fade-in {
            animation: fadeIn 0.3s;
        }
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        .category-item:hover .category-img {
            transform: scale(1.1);
            border-color: #ec4899;
        }
        .product-card:hover {
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1);
            transform: translateY(-2px);
        }
        .product-card {
            transition: all 0.2s ease-in-out;
        }
        .cart-badge {
            min-width: 24px;
            height: 24px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
        }
    </style>
{% endblock %}

{% block content %}
<div class="container mx-auto px-4 py-8">
    <!-- 面包屑导航 -->
    <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-8">
        <div>
            <h1 class="text-3xl font-bold text-gray-800 mb-2">
                {% if current_category %}
                    {{ current_category.name }}
                {% else %}
                    所有商品
                {% endif %}
            </h1>
            <nav class="flex text-sm text-gray-500">
                <a href="/" class="hover:text-pink-500">首页</a>
                <span class="mx-2">/</span>
                <a href="/goods/" class="hover:text-pink-500">商品</a>
                {% if current_category %}
                    <span class="mx-2">/</span>
                    <span class="text-pink-500">{{ current_category.name }}</span>
                {% endif %}
            </nav>
        </div>
        
        <!-- 购物车按钮 -->
        <a href="/cart/show_cart/" class="flex items-center bg-white px-4 py-2 rounded-full shadow-sm hover:shadow-md mt-4 md:mt-0">
            <i class="fas fa-shopping-cart text-pink-500 mr-2"></i>
            <span class="text-gray-700">购物车</span>
            <span class="ml-2 bg-pink-500 text-white text-xs font-bold rounded-full cart-badge">
                {{ cart_goods_count|default:0 }}
            </span>
        </a>
    </div>

    <!-- 主内容区 -->
    <div class="flex flex-col lg:flex-row gap-8">
        <!-- 左侧分类导航 - 修复了子分类可能为空的情况 -->
        <div class="w-full lg:w-1/5 bg-white rounded-lg shadow p-4">
            <h3 class="text-lg font-semibold text-gray-700 mb-4 border-b pb-2">商品分类</h3>
            <ul class="space-y-2">
                <li>
                    <a href="/goods/" class="block py-2 px-3 rounded hover:bg-gray-100 {% if not current_category %}bg-pink-50 text-pink-600 font-medium{% endif %}">
                        所有商品
                    </a>
                </li>
                {% for category in categories %}
                    <li>
                        <a href="?cag={{category.id}}" class="block py-2 px-3 rounded hover:bg-gray-100 {% if current_category.id == category.id %}bg-pink-50 text-pink-600 font-medium{% endif %}">
                            {{ category.name }}
                            {% if category.products.count > 0 %}
                                <span class="float-right text-xs text-gray-400">{{ category.products.count }}件</span>
                            {% endif %}
                        </a>
                        
                        <!-- 子分类（增加了空值检查） -->
                        {% if category.subcategories.exists %}
                            <ul class="ml-4 mt-1 space-y-1">
                                {% for subcategory in category.subcategories.all %}
                                    <li>
                                        <a href="?cag={{subcategory.id}}" class="block py-1 px-3 text-sm rounded hover:bg-gray-100 {% if current_category.id == subcategory.id %}bg-pink-50 text-pink-600 font-medium{% endif %}">
                                            {{ subcategory.name }}
                                            {% if subcategory.products.count > 0 %}
                                                <span class="float-right text-xs text-gray-400">{{ subcategory.products.count }}件</span>
                                            {% endif %}
                                        </a>
                                    </li>
                                {% endfor %}
                            </ul>
                        {% endif %}
                    </li>
                {% endfor %}
            </ul>
        </div>

        <!-- 右侧商品列表 -->
        <div class="w-full lg:w-4/5">
            {% if page_data and page_data.object_list %}
                <!-- 商品排序和筛选 -->
                <div class="bg-white rounded-lg shadow p-4 mb-6">
                    <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
                        <div class="text-sm text-gray-500">
                            共 <span class="font-medium text-pink-500">{{ paginator.count }}</span> 件商品
                        </div>
                        {% comment %}
                        <div class="flex items-center space-x-2">
                            <span class="text-sm text-gray-500">排序:</span>
                            <select class="border rounded py-1 px-2 text-sm focus:outline-none focus:ring-1 focus:ring-pink-500">
                                <option>默认排序</option>
                                <option>价格从低到高</option>
                                <option>价格从高到低</option>
                                <option>新品优先</option>
                                <option>销量优先</option>
                            </select>
                        </div>
                        {% endcomment %}
                    </div>
                </div>

                <!-- 商品网格（确保图片路径安全） -->
                <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-3 lg:grid-cols-4 gap-6">
                    {% for product in page_data.object_list %}
                        <div class="product-card bg-white rounded-lg shadow overflow-hidden transition duration-300">
                            <div class="relative">
                                <a href="/detail/{{ product.id }}/">
                                    {% if product.image_url %}
                                        <img 
                                            src="{% get_media_prefix %}{{ product.image_url }}" 
                                            alt="{{ product.name }}"
                                            class="w-full h-48 object-cover"
                                            onerror="this.src='{% static 'images/default-product.png' %}';this.onerror=null;"
                                        >
                                    {% else %}
                                        <div class="w-full h-48 bg-gray-100 flex items-center justify-center">
                                            <i class="fas fa-image text-gray-300 text-4xl"></i>
                                        </div>
                                    {% endif %}
                                    
                                    <!-- 商品标签（增加了日期格式检查） -->
                                    {% if product.shelf_life_end_date %}
                                        <div class="absolute top-2 left-2 bg-yellow-100 text-yellow-800 text-xs px-2 py-1 rounded-full">
                                            <i class="fas fa-clock mr-1"></i>
                                            {{ product.shelf_life_end_date|date:"Y-m-d" }}到期
                                        </div>
                                    {% endif %}
                                </a>
                                
                                <!-- 添加购物车按钮（确保product.id存在） -->
                                <button onclick="addToCart({{ product.id }})" 
                                        class="absolute bottom-2 right-2 bg-pink-500 text-white p-2 rounded-full shadow hover:bg-pink-600 focus:outline-none transition">
                                    <i class="fas fa-cart-plus"></i>
                                </button>
                            </div>
                            
                            <div class="p-4">
                                <a href="/detail/{{ product.id }}/" class="block">
                                    <h3 class="text-gray-800 font-medium mb-1 truncate">{{ product.name }}</h3>
                                    <p class="text-xs text-gray-500 mb-2 line-clamp-2">
                                        {{ product.description|default:"暂无描述" }}
                                    </p>
                                    
                                    <div class="flex justify-between items-center mt-3">
                                        <div>
                                            <span class="text-pink-600 font-bold">¥{{ product.price|floatformat:2 }}</span>
                                            {% if product.cost_price and product.price > product.cost_price %}
                                                <span class="ml-2 text-xs text-gray-400 line-through">¥{{ product.cost_price|floatformat:2 }}</span>
                                            {% endif %}
                                        </div>
                                        <span class="text-xs px-2 py-1 bg-gray-100 rounded">{{ product.unit|default:"件" }}</span>
                                    </div>
                                </a>
                            </div>
                        </div>
                    {% endfor %}
                </div>

                <!-- 分页（确保分页对象存在） -->
                {% if page_data.paginator.num_pages > 1 %}
                    <div class="mt-8 flex justify-center">
                        <nav class="inline-flex rounded-md shadow">
                            {% if page_data.has_previous %}
                                <a href="?cag={% if current_category %}{{ current_category.id }}{% endif %}&page={{ page_data.previous_page_number }}"
                                   class="px-3 py-2 rounded-l-md border border-gray-300 bg-white text-gray-500 hover:bg-gray-50">
                                    <i class="fas fa-angle-left"></i>
                                </a>
                            {% endif %}
                            
                            {% for num in page_data.paginator.page_range %}
                                {% if num == page_data.number %}
                                    <span class="px-3 py-2 border-t border-b border-gray-300 bg-pink-500 text-white">
                                        {{ num }}
                                    </span>
                                {% else %}
                                    <a href="?cag={% if current_category %}{{ current_category.id }}{% endif %}&page={{ num }}"
                                       class="px-3 py-2 border-t border-b border-gray-300 bg-white text-gray-500 hover:bg-gray-50">
                                        {{ num }}
                                    </a>
                                {% endif %}
                            {% endfor %}
                            
                            {% if page_data.has_next %}
                                <a href="?cag={% if current_category %}{{ current_category.id }}{% endif %}&page={{ page_data.next_page_number }}"
                                   class="px-3 py-2 rounded-r-md border border-gray-300 bg-white text-gray-500 hover:bg-gray-50">
                                    <i class="fas fa-angle-right"></i>
                                </a>
                            {% endif %}
                        </nav>
                    </div>
                {% endif %}
            {% else %}
                <!-- 没有商品的提示（使用静态文件加载） -->
                <div class="bg-white rounded-lg shadow p-8 text-center">
                    <img src="{% static 'img/empty-product.png' %}" alt="空商品" class="w-48 h-48 mx-auto mb-6">
                    <h3 class="text-xl font-medium text-gray-700 mb-2">
                        {% if current_category %}
                            当前分类{{ current_category.name }}暂无商品
                        {% else %}
                            暂时没有商品
                        {% endif %}
                    </h3>
                    
                    <!-- 如果没有商品展示其他推荐分类 -->
                    {% if other_categories %}
                        <div class="mt-6">
                            <h4 class="text-lg text-gray-600 mb-4">您可能感兴趣的其他分类：</h4>
                            <div class="flex flex-wrap justify-center gap-4">
                                {% for category in other_categories %}
                                    <a href="?cag={{ category.id }}" class="px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-full transition">
                                        {{ category.name }}
                                        <span class="text-sm text-gray-500">({{ category.product_count|default:0 }})</span>
                                    </a>
                                {% endfor %}
                            </div>
                        </div>
                    {% else %}
                        <p class="text-gray-500 mb-6">您可以浏览其他分类或稍后再来看看</p>
                    {% endif %}
                    
                    <div class="mt-6">
                        <a href="/goods/" class="px-4 py-2 bg-pink-500 text-white rounded-md hover:bg-pink-600 transition">
                            浏览所有商品
                        </a>
                    </div>
                </div>
            {% endif %}
        </div>
    </div>
</div>

<!-- 通知弹窗容器 -->
<div id="toast" class="fixed top-5 right-5 z-50"></div>

<script>
    // 加入购物车函数（确保CSRF安全）
    function addToCart(productId) {
        const csrftoken = getCookie('csrftoken');
        
        fetch(`/cart/add/${productId}/`, {
            method: 'POST',
            headers: {
                'X-CSRFToken': csrftoken,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                'quantity': 1
            })
        })
        .then(response => response.json())
        .then(data => {
            if(data.status === 'success') {
                // 更新购物车数量（确保DOM元素存在）
                const cartBadge = document.querySelector('.cart-badge');
                if(cartBadge) {
                    cartBadge.textContent = data.cart_count || 0;
                }
                // 显示成功通知
                showToast('商品已成功加入购物车', 'success');
            } else {
                // 显示错误通知
                showToast(data.message || '加入购物车失败', 'error');
                
                // 如果需要登录，跳转到登录页面
                if(data.code === 'login_required') {
                    setTimeout(() => {
                        window.location.href = '/user/login/?next=' + encodeURIComponent(window.location.pathname);
                    }, 1500);
                }
            }
        })
        .catch(error => {
            showToast('网络错误，请稍后重试', 'error');
            console.error('Error:', error);
        });
    }

    // 显示通知弹窗
    function showToast(message, type = 'info') {
        const toastContainer = document.getElementById('toast');
        if(!toastContainer) return;
        
        const toast = document.createElement('div');
        
        // 设置基本样式
        toast.className = `flex items-center p-4 mb-3 rounded-lg shadow-lg fade-in 
            ${type === 'success' ? 'bg-green-50 text-green-700' : ''}
            ${type === 'error' ? 'bg-red-50 text-red-700' : ''}`;
            
        // 设置图标
        const icon = document.createElement('i');
        icon.className = `mr-2 ${type === 'success' ? 'fas fa-check-circle' : 'fas fa-exclamation-circle'}`;
        toast.appendChild(icon);
        
        // 设置消息文本
        const messageText = document.createElement('span');
        messageText.textContent = message;
        toast.appendChild(messageText);
        
        // 添加到容器
        toastContainer.appendChild(toast);
        
        // 5秒后自动移除
        setTimeout(() => {
            toast.classList.add('opacity-0', 'transition-opacity', 'duration-300');
            setTimeout(() => toast.remove(), 300);
        }, 5000);
    }

    // 获取CSRF token
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
</script>
{% endblock %}
